package cn.huixh.blindbox.config;

import cn.huixh.blindbox.common.FastJson2JsonRedisSerializer;
import cn.huixh.blindbox.utils.RedisUtil;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author huixh
 * @version 1.0
 * @date 2022/5/6 21:04
 */
@Configuration
public class RedisConfig {

    @Bean("redisTemplate")
    public RedisTemplate< String, Object > redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate< String, Object > template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        //Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        //使用Fastjson2JsonRedisSerializer来序列化和反序列化redis的value值 by zhengkai
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 注入封装RedisTemplate 给RedisUtil提供操作类
     *
     * @param redisTemplate redisTemplate
     * @return RedisUtil
     * @date 2020/3/13 11：20
     */
    @Bean(name = "redisUtil")
    public RedisUtil redisUtil(RedisTemplate< String, Object > redisTemplate) {
        return new RedisUtil(redisTemplate);
    }
}
